package org.tinygroup.channel.test.protocol;

import org.tinygroup.channel.protocol.ProtocolListener;
import org.tinygroup.channel.protocol.impl.ProtocolListenerChain;
import org.tinygroup.commons.tools.StringUtil;
import org.tinygroup.context.Context;

import com.google.common.util.concurrent.RateLimiter;

public class ObjectProtocolInListener implements
		ProtocolListener<Object, Object> {
//	private final static String RATE_LIMIT = "rate_limit";
	private  RateLimiter rateLimiter = null;
	private String rate;
	
	public String getRate() {
		return rate;
	}

	public void setRate(String rate) {
		this.rate = rate;
		if(StringUtil.isBlank(rate)){
			return;
		}
		rateLimiter = RateLimiter.create(Double.parseDouble(rate));
	}

	public void pre(Object r, Context context, ProtocolListenerChain chain) {
		if(rateLimiter!=null&&!rateLimiter.tryAcquire()){
			throw new RuntimeException("达到流量限制");
		}
		chain.pre(r, context);
	}

	public void post(Object r, Object r1, Context context,
			ProtocolListenerChain chain) {
		
		chain.post(r, r1, context);
	}

	public String getId() {
		return null;
	}

	public void setId(String id) {
	}

	

}
